package com.ruoyi.work.utils;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * 图片透明底工具类
 *
 * @author fengcheng
 */
public class TransparentImageUtils {

    /**
     * 将背景替换为透明
     *
     * @param path        图片路径
     * @param newFilePath 新图片保存路径
     * @return
     * @author fengcheng
     */
    public static boolean changeImgColor(String path, String newFilePath) {
        try {
            File file = new File(path);
            String fileName = file.getName();
            BufferedImage bi = ImageIO.read(file);
            Image image = (Image) bi;
            //将原图片的二进制转化为ImageIcon
            ImageIcon imageIcon = new ImageIcon(image);
            int width = imageIcon.getIconWidth();
            int height = imageIcon.getIconHeight();

            //图片缓冲流
            BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
            Graphics2D graphics2D = (Graphics2D) bufferedImage.getGraphics();
            graphics2D.drawImage(imageIcon.getImage(), 0, 0, imageIcon.getImageObserver());

            int alpha = 255;

            //这个背景底色的选择，我这里选择的是比较偏的位置，可以修改位置。背景色选择不知道有没有别的更优的方式（比如先过滤一遍获取颜色次数最多的，但是因为感觉做起来会比较复杂没去实现），如果有可以评论。
            int RGB = bufferedImage.getRGB(width - 1, height - 1);

            for (int i = bufferedImage.getMinX(); i < width; i++) {
                for (int j = bufferedImage.getMinY(); j < height; j++) {

                    int rgb = bufferedImage.getRGB(i, j);

                    int r = (rgb & 0xff0000) >> 16;
                    int g = (rgb & 0xff00) >> 8;
                    int b = (rgb & 0xff);
                    int R = (RGB & 0xff0000) >> 16;
                    int G = (RGB & 0xff00) >> 8;
                    int B = (RGB & 0xff);
                    //a为色差范围值，渐变色边缘处理，数值需要具体测试，50左右的效果比较可以
                    int a = 45;
                    if (Math.abs(R - r) < a && Math.abs(G - g) < a && Math.abs(B - b) < a) {
                        alpha = 0;
                    } else {
                        alpha = 255;
                    }
                    rgb = (alpha << 24) | (rgb & 0x00ffffff);
                    bufferedImage.setRGB(i, j, rgb);
                }
            }

            ImageIO.write(bufferedImage, "png", new File(newFilePath));
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }
}

